package com.szgr.baoyin.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.szgr.baoyin.MainActivity;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.model.CardType;
import com.szgr.baoyin.model.DYCard;
import com.szgr.baoyin.model.DYCard1;
import com.szgr.baoyin.myview.WheelView;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.DialogUtils;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.RLog;
import com.szgr.baoyin.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class DuYinCardPayActivity extends BaseActivity {

    private TextView tv_name;
    private TextView tv_cardNumber;
    private ImageView img_btn;
    private TextView tv_cardName;
    private TextView tv_cardLevel;
    private TextView tv_remainMoney;
    private TextView tv_discount1;
    private TextView tv_discount2;
    private TextView tv_oldMoney;
    private TextView tv_newMoney;
    private String pay_sn;
    private List<DYCard1> data;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 33:
                    DialogUtils.hideLoadingDialog();
                    if(data.size() > 0){
                        selectCard = data.get(0);
                        showPage(selectCard);
                    }else{
                        ToastUtils.showToast("您还没有购买都银卡");
                        finish();
                    }
                    break;
                case 34:
                    DialogUtils.hideLoadingDialog();
                    ToastUtils.showToast("您还没有购买都银卡");
                    finish();
                    break;
                case 44:
                    ToastUtils.showToast("支付成功");
                    Intent intent = new Intent(DuYinCardPayActivity.this, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    finish();
                    break;
            }
        }
    };
    private LinearLayout menuView;
    private int index = 1;
    private Dialog menuDialog;
    private WheelView wheelView;
    private DYCard1 selectCard;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_du_yin_card_pay);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initActionBar() {
        actionBarTitle.setText("都银卡抵扣");
    }

    @Override
    public void initView() {
        data = new ArrayList<>();
        tv_name = (TextView) findViewById(R.id.pay_card_name);
        tv_cardNumber = (TextView) findViewById(R.id.pay_card_number);
        img_btn = (ImageView) findViewById(R.id.pay_card_button);
        img_btn.setOnClickListener(this);
        tv_cardName = (TextView) findViewById(R.id.pay_card_name1);
        tv_cardLevel = (TextView) findViewById(R.id.pay_card_level);
        tv_remainMoney = (TextView) findViewById(R.id.pay_card_remain_money);
        tv_discount1 = (TextView) findViewById(R.id.pay_card_discount1);
        tv_discount2 = (TextView) findViewById(R.id.pay_card_discount2);
        tv_oldMoney = (TextView) findViewById(R.id.pay_card_old_money);
        tv_newMoney = (TextView) findViewById(R.id.pay_card_new_money);
        Button btn_submit = (Button) findViewById(R.id.my_order_detail_submit1);
        btn_submit.setOnClickListener(this);

        initDialog("选择都银卡");

        Intent intent = getIntent();
        if(intent != null && intent.hasExtra("pay_sn")){
            pay_sn = intent.getStringExtra("pay_sn");
            payStep3(pay_sn);
        }
    }

    private void payStep3(final String pay_sn) {
        DialogUtils.showLoadingDialog(this,"正在加载中...");
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_PAY_STEP3,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        RLog.s("---step3--->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject datas = jsonObject.getJSONObject("datas");
                            JSONObject card_list = datas.getJSONObject("card_list");
                            Iterator<String> keys = card_list.keys();
                            Gson gson = new Gson();
                            while (keys.hasNext()){
                                JSONObject jsonObject1 = card_list.getJSONObject(keys.next());
                                DYCard1 dyCard = gson.fromJson(jsonObject1.toString(), DYCard1.class);

                                JSONObject card_config = jsonObject1.getJSONObject("card_config");
                                Iterator<String> keys1 = card_config.keys();
                                List<CardType.CardConfig> configs = new ArrayList<>();
                                while (keys1.hasNext()){
                                    JSONObject jsonObject2 = card_config.getJSONObject(keys1.next());
                                    CardType.CardConfig cardConfig = gson.fromJson(jsonObject2.toString(), CardType.CardConfig.class);
                                    configs.add(cardConfig);
                                }
                                dyCard.setCard_configs(configs);
                                data.add(dyCard);
                            }
                            mHandler.obtainMessage(33).sendToTarget();
                        } catch (JSONException e) {
                            mHandler.obtainMessage(34).sendToTarget();
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                map.put("pay_sn",pay_sn);
                RLog.s("---params--->" + map.toString());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.action_bar_left:
                finish();
                break;
            case R.id.my_order_detail_submit1:
                if(selectCard != null) {
                    submitPay(pay_sn, selectCard.getId());
                }else{
                    ToastUtils.showToast("您还没有都银卡");
                }
                break;
            case R.id.pay_card_button:
                List<String> strs = new ArrayList<>();
                if(data.size() > 0){
                    for (DYCard1 dyCard : data) {
                        CardType card = dyCard.getCard();
                        strs.add(card.getCard_name() + ":" + dyCard.getCard_sn());
                    }
                }
                if(strs.size() > 1) {
                    wheelView.setItems(strs);
                    wheelView.setSeletion(0);
                    menuDialog.show();
                }
                break;
        }
    }

    private void submitPay(final String pay_sn, final String id) {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_DYCARD_PAY,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        RLog.s("----pay step3--->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String datas = jsonObject.getString("datas");
                            if("支付成功".equals(datas)){
                                mHandler.obtainMessage(44).sendToTarget();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                map.put("pay_sn",pay_sn);
                map.put("card_id",id);
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    public void initDialog(String title){
        menuView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.layout_wheel_view,null);
        View confirm = menuView.findViewById(R.id.confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectCard = data.get(index - 1);
                showPage(selectCard);

                menuDialog.dismiss();
                index = 1;
            }
        });
        View cancel = menuView.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menuDialog.dismiss();
                index = 1;
            }
        });
        TextView tv_title = (TextView) menuView.findViewById(R.id.title);
        tv_title.setText(title);
        wheelView = (WheelView) menuView.findViewById(R.id.wheel_view);

        wheelView.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                index = selectedIndex;
            }
        });
        menuDialog = MyTool.getMenuDialog(this, menuView);
    }

    private void showPage(DYCard1 selectCard){
        CardType card = selectCard.getCard();
        tv_name.setText(card.getCard_name());
        tv_cardNumber.setText(selectCard.getCard_sn());

        tv_cardName.setText(card.getCard_name());
        tv_cardLevel.setText(selectCard.getCard_id());
        tv_remainMoney.setText(selectCard.getCard_balance());
        tv_oldMoney.setText("没传");
        tv_newMoney.setText(selectCard.getCard_cost());

        List<CardType.CardConfig> card_config = selectCard.getCard_configs();
        for (CardType.CardConfig config : card_config) {
            if("12".equals(config.getStore_goods_class())){
                tv_discount1.setText("配件 " + MyTool.formatDouble(Double.parseDouble(config.getCard_discount()) * 10 ) + "折");
            }else if("13".equals(config.getStore_goods_class())){
                tv_discount2.setText("维保 " + MyTool.formatDouble(Double.parseDouble(config.getCard_discount()) * 10 ) + "折");
            }
        }
    }
}
